<template>
  <!--
      	作者：luoyiming
      	时间：2019-06-04
      	描述：插件中心-优惠券-优惠券列表-修改优惠券
      -->
  <div v-loading="loading">
    <!--form表单-->
    <el-form size="small" ref="form" :model="form" label-width="200px">
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="基本信息" name="1"></el-tab-pane>
        <!--        <el-tab-pane label="适用商品" name="2"></el-tab-pane>-->
      </el-tabs>

      <template v-if="activeName=='1'">
        <!--修改优惠券-->
        <div class="common-form">修改优惠券</div>

        <el-form-item label="优惠券名称" prop="name" :rules="[{ required: true, message: ' ' }]">
          <el-input v-model="form.name" placeholder="请输入优惠券名称"></el-input>
          <div class="tips">例如：满100减10</div>
        </el-form-item>
        <el-form-item label="优惠券封面(高宽122x193)">
          <el-row>
            <el-button icon="el-icon-picture-outline" @click="openUpload('image')">选择图片</el-button>
            <div v-if="form.image!=''" class="img mt10">
              <img :src="form.image" width="100" height="100"/>
              <a href="javascript:void(0);" class="delete-btn" @click.stop="deleteImg()">删除<i
                class="el-icon-close"></i></a>
            </div>
          </el-row>
        </el-form-item>
        <el-form-item label="领取优惠券封面(高宽122x193)">
          <el-row>
            <el-button icon="el-icon-picture-outline" @click="openUpload('image_get')">选择图片</el-button>
            <div v-if="form.image_get!=''" class="img mt10">
              <img :src="form.image_get" width="100" height="100"/>
              <a href="javascript:void(0);" class="delete-btn" @click.stop="deleteImgGet()">删除<i
                class="el-icon-close"></i></a>
            </div>
          </el-row>
        </el-form-item>
        <!--        <el-form-item label="优惠券颜色">-->
        <!--          <el-radio-group v-model="form.color">-->
        <!--            <el-radio :label="10">蓝色</el-radio>-->
        <!--            <el-radio :label="20">红色</el-radio>-->
        <!--            <el-radio :label="30">紫色</el-radio>-->
        <!--            <el-radio :label="40">黄色</el-radio>-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
        <el-form-item label="优惠券类型">
          <el-radio-group v-model="form.coupon_type">
            <el-radio :label="10">满减券</el-radio>
            <el-radio :label="20">折扣券</el-radio>
            <el-radio :label="30">新人满减券</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="form.coupon_type == 10 || form.coupon_type == 30 ">
          <el-form-item label="减免金额">
            <el-input v-model="form.reduce_price" placeholder="请输入减免金额" type="number"></el-input>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label="折扣率 ">
            <el-input v-model="form.discount" placeholder="请输入折扣率" type="number"></el-input>
            <div class="tips">折扣率范围0-10，9.5代表9.5折，整数或1位小数</div>
          </el-form-item>
        </div>

        <el-form-item label="最低消费金额">
          <el-input v-model="form.min_price" placeholder="请输入最低消费金额" type="number"></el-input>
        </el-form-item>

        <el-form-item label="到期类型">
          <el-radio-group v-model="form.expire_type">
            <el-radio :label="10">领取后生效</el-radio>
            <el-radio :label="20">固定时间</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="form.expire_type == 10">
          <el-form-item label="有效天数">
            <el-input v-model="form.expire_day" placeholder="请输入有效天数" type="number"></el-input>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label="有效时间">
            <el-date-picker v-model="form.active_time" type="daterange" align="right" unlink-panels
                            value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            :picker-options="pickerOptions0"></el-date-picker>
          </el-form-item>
        </div>
        <el-form-item label="发放总数量 " prop="total_num" :rules="[{ required: true, message: ' ' }]">
          <el-input v-model="form.total_num" placeholder="请输入发放总数量" type="number"></el-input>
          <div class="tips">限制领取的优惠券数量，-1为不限制</div>
        </el-form-item>
        <el-form-item label="是否显示在领券中心">
          <el-radio-group v-model="form.show_center">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">不显示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序">
          <el-input type="number" v-model="form.sort" placeholder="请输入排序"></el-input>
        </el-form-item>
      </template>
      <template v-if="activeName=='1'||activeName=='3'">
        <div class="common-form">指定商户</div>
        <el-form-item label="选择">
          <el-radio-group v-model="form.supplier_range" @change="changeSupplierRange">
            <el-radio :label="2">指定商户</el-radio>
            <el-radio :label="1">指定地区</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.supplier_range==1" label="指定地区">
          <el-cascader
            v-model="form.region_id"
            :options="regions"
            :props="{value:'id',label:'name',checkStrictly: true }"
            clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item v-if="form.supplier_range==2">
          <el-button class="mb10" @click="is_supplier=true" type="primary" plain>设置商户
          </el-button>
          <el-table size="mini" v-if="supplier_list.length>0" :data="supplier_list" max-height="400" border
                    style="width: 800px">
            <el-table-column prop="shop_supplier_id" label="商户ID" width="70"></el-table-column>
            <el-table-column prop="name" label="商户名称" width="110"></el-table-column>
            <el-table-column prop="superUser.user_name" label="登录账号" width="110"></el-table-column>
            <el-table-column prop="region_name" label="所属地区" width="200"></el-table-column>
            <el-table-column prop="proxy_name" label="区域代理" width="110"></el-table-column>
            <el-table-column prop="link_phone" label="联系电话"></el-table-column>
            <el-table-column label="操作" width="80">
              <template slot-scope="scope">
                <el-button @click="is_supplier=true" type="text" size="small">重新选择</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="" v-if="form.apply_range==30">
          <el-button class="mb10" @click="is_category=true" type="primary" plain>添加分类
          </el-button>
          <div>
            <el-tag class=" mr10 mb10" type="info" v-if="category_list.first.length>0"
                    v-for="(item,index) in category_list.first"
                    :key="item.category_id">
              {{ item.parent ? item.parent + '→' + item.name : item.name }}
            </el-tag>
            <el-tag class=" mr10 mb10" type="info" v-if="category_list.second.length>0"
                    v-for="(item,index) in category_list.second" :key="item.category_id">
              {{ item.parent ? item.parent + '→' + item.name : item.name }}
            </el-tag>
          </div>
        </el-form-item>
      </template>
      <template v-if="activeName=='1'">
        <div class="common-form">适用商品</div>
        <el-form-item label="选择">
          <el-radio-group v-model="form.apply_range">
            <el-radio :label="10">全部商品</el-radio>
            <el-radio :label="20">
              <span>指定商品</span>
            </el-radio>
            <el-radio :label="30">
              <span>指定分类</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.apply_range==20">
          <el-button class="mb10" @click="showAddProduct" type="primary" plain>添加商品
          </el-button>
          <el-table v-if="product_list.length>0" :data="product_list" max-height="400" border style="width: 100%">
            <el-table-column prop="product_id" label="ID" width="180">
            </el-table-column>
            <el-table-column prop="product_name" label="商品名称" width="180">
            </el-table-column>
            <el-table-column prop="image" label="图片">
              <template slot-scope="scope">
                <img v-img-url="hasImages(scope.row.product_image)" alt="" width="50px"/>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="deleteClick(scope.$index)" type="text" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="" v-if="form.apply_range==30">
          <el-button class="mb10" @click="is_category=true" type="primary" plain>添加分类
          </el-button>
          <div>
            <el-tag class=" mr10 mb10" type="info" v-if="category_list.first.length>0"
                    v-for="(item,index) in category_list.first" :key="item.category_id">
              {{ item.parent ? item.parent + '→' + item.name : item.name }}
            </el-tag>
            <el-tag class=" mr10 mb10" type="info" v-if="category_list.second.length>0"
                    v-for="(item,index) in category_list.second" :key="item.category_id">
              {{ item.parent ? item.parent + '→' + item.name : item.name }}
            </el-tag>
          </div>
        </el-form-item>
      </template>
      <!--提交-->
      <div class="common-button-wrapper">
        <el-button type="info" size="small" @click="cancelFunc" :loading="loading">取消</el-button>
        <el-button type="primary" size="small" @click="onSubmit" :loading="loading">提交</el-button>
      </div>
    </el-form>
    <!--选择商品-->
    <Product :isproduct="is_product" :excludeIds="exclude_ids" :islist="true" @closeDialog="closeProductFunc"></Product>
    <Supplier :issupplier="is_supplier" :excludeIds="supplier_exclude_ids" :islist="false"
              @closeDialog="closeSupplierFunc"></Supplier>
    <Category :is_category="is_category" :excludeIds='category_ids' @close="closeCategoryFunc"></Category>
    <!--上传图片组件-->
    <Upload v-if="isupload" :isupload="isupload" :type="type" @returnImgs="returnImgsFunc">上传图片</Upload>
  </div>
</template>

<script>
import CouponApi from '@/api/coupon.js';
import Product from '@/components/product/Product.vue';
import Category from '@/components/category/category.vue';
import Upload from '@/components/file/Upload';
import Supplier from '@/components/supplier/supplier.vue';
import IndexApi from "@/api/index.js";

import {
  formatModel
} from '@/utils/base.js'
import SupplierApi from "@/api/supplier";

export default {
  components: {
    Product,
    Category,
    Upload,
    Supplier
  },
  data() {
    return {
      isupload: false,
      regions: [],
      activeName: '1',
      /*form表单数据*/
      form: {
        /*优惠券ID*/
        coupon_id: '',
        /*优惠券名称*/
        name: '',
        /*优惠券颜色*/
        color: '',
        /*优惠券类型*/
        coupon_type: '',
        /*减免金额*/
        reduce_price: '',
        /*折扣率*/
        discount: '',
        /*最低消费金额*/
        min_price: '',
        /*到期类型*/
        expire_type: '',
        /*有效天数*/
        expire_day: '',
        /*有效期*/
        active_time: '',
        /*发放量*/
        total_num: '',
        show_center: 1,
        /*排序*/
        sort: 1,
        apply_range: 10,
        image: '',
        image_get: '',
        supplier_range: 2,
        region_id: [],
        supplier_exclude_ids: []
      },
      list: {},
      /*是否正在加载*/
      loading: true,
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; //如果没有后面的-8.64e7就是不可以选择今天的
        }
      },
      is_category: false,
      is_product: false,
      is_supplier: false,
      exclude_ids: [],
      product_list: [],
      supplier_exclude_ids: [],
      supplier_list: [],
      category_list: {
        second: [],
        first: []
      },
      category_ids: []
    };
  },
  created() {
    let coupon_id = this.$route.query.coupon_id;
    this.getRegions();
    this.getData(coupon_id);
  },
  watch: {
    "form.region_id"() {
     if(!this.loading) this.changeSupplierRange(2);
    }
  },
  methods: {
    getRegions() {
      let self = this;
      let Params = {glv:1};
      IndexApi.getProxyRegionList(Params, true)
        .then(res => {
          self.regions = [];
          Object.keys(res.data.regions).forEach(key => {
            self.regions.push(res.data.regions[key]);
          });
        })
        .catch(error => {});
      // let self = this;
      // SupplierApi.getTreeList({disabled: true}, true)
      //   .then(res => {
      //     self.regions = [];
      //     Object.keys(res.data.regions).forEach((key) => {
      //       self.regions.push(res.data.regions[key]);
      //     });
      //     // self.$nextTick(() => {
      //     //   if (self.regions.length > 0) {
      //     //     self.form.region_id = self.regions[0].region_id;
      //     //   }
      //     // })
      //   }).catch(error => {

      // });
    },
    deleteImg() {
      this.form.image = '';
    },
    deleteImgGet() {
      this.form.image_get = '';
    },
    /*上传*/
    openUpload(e) {
      this.type = e;
      this.isupload = true;
    },
    /*获取图片*/
    returnImgsFunc(e) {
      if (e != null && e.length > 0) {
        if (this.type == 'image') {
          this.form.image = e[0].file_path;
        }
        if (this.type == 'image_get') {
          this.form.image_get = e[0].file_path;
        }
      }
      this.isupload = false;
    },
    hasImages(e) {
      if (e) {
        return e;
      } else {
        return '';
      }
    },
    getData(coupon_id) {
      let self = this;
      CouponApi.couponDetail({
          coupon_id: coupon_id
        },
        true
      )
        .then(data => {
          let obj = {};
          obj = data.data.detail;
          //选中
          obj.color = data.data.detail.color.value;
          obj.coupon_type = data.data.detail.coupon_type.value;
          self.form = formatModel(self.form, obj);
          if (self.form.apply_range == 20) {
            self.exclude_ids = data.data.detail.product_ids;
            for (let i = 0; i < self.exclude_ids.length; i++) {
              self.exclude_ids[i] = parseInt(self.exclude_ids[i]);
            }
            self.product_list = data.data.detail.product_list;
          }
          if (self.form.apply_range == 30) {
            self.category_list = data.data.detail.category_list;
          }

          if (self.form.supplier_range == 2 && data.data.detail.supplier_list) {
            self.supplier_list = [data.data.detail.supplier_list];
            self.supplier_exclude_ids = [data.data.detail.shop_supplier_id];
          }
          self.$nextTick(() => {
            self.loading = false;
          })
        })
        .catch(error => {
          self.loading = false;

        });
    },

    /*修改*/
    onSubmit() {
      let self = this;
      let form = self.form;
      form.product_ids = self.exclude_ids;
      form.category_list = self.category_list;
      form.supplier_exclude_ids = self.supplier_exclude_ids;
      self.$refs.form.validate(valid => {
        if (valid) {
          // 如果是折扣，则判断折扣是否大于0小于10
          if (form.coupon_type == 20) {
            if (form.discount <= 0 || form.discount >= 10) {
              self.$message({
                message: '折扣率介于0和10之间',
                type: 'error'
              });
              return;
            }
          }
          self.loading = true;
          CouponApi.editCoupon(form, true)
            .then(data => {
              self.loading = false;
              self.$message({
                message: '恭喜你，修改成功',
                type: 'success'
              });
              self.$router.push('/plus/coupon/index');
            })
            .catch(error => {
              self.loading = false;
            });
        } else {
          self.loading = false;
        }
      });
    },
    closeCategoryFunc(e) {
      let self = this;
      self.is_category = false;
      if (e) {
        self.category_list = e;
      }
    },
    /*关闭商品*/
    closeProductFunc(e) {
      let self = this;
      self.is_product = e.openDialog;
      if (e.type == 'success') {
        e.params.forEach((item, index) => {
          let params = {
            product_id: item.product_id,
            product_name: item.product_name,
            product_image: item.product_image,
          }
          self.exclude_ids.push(params.product_id)
          self.product_list.push(params);
        })
      }
    },
    /*关闭商户*/
    closeSupplierFunc(e) {
      let self = this;
      self.is_supplier = e.openDialog;
      if (e.type == 'success') {
        self.supplier_exclude_ids = [];
        self.supplier_list = [];
        e.params.forEach((item, index) => {
          self.supplier_exclude_ids.push(item.shop_supplier_id)
          self.supplier_list.push(item);
        })
        if (this.form.apply_range == 20 && this.product_list.length) {
          self.exclude_ids = [];
          self.product_list = [];
          this.$message.success("商户信息已变更，请重新设置指定商品")
        }
      }
    },
    deleteClick(e) {
      this.exclude_ids.splice(e, 1);
      this.product_list.splice(e, 1);
    },
    /*取消*/
    cancelFunc() {
      this.$router.push({
        path: '/plus/coupon/index',
      });
    },
    showAddProduct() {
      let self = this;
      if (this.form.supplier_range == 1) {
        if (this.form.region_id == 0) {
          this.$message.error("请先设置指定商户");
          return false;
        }
        this.supplier_exclude_ids = [];
        this.region_ids = [this.form.region_id];
        this.is_product = true;
        return true;
      }
      if (this.form.supplier_range == 2) {
        if (!this.supplier_list || this.supplier_list.length == 0) {
          this.$message.error("请先设置指定商户");
          return false;
        }
        this.supplier_exclude_ids = [];
        this.supplier_list.forEach((item) => {
          self.supplier_exclude_ids.push(item.shop_supplier_id)
        })
        this.is_product = true;
        return true;
      }
    },
    changeSupplierRange(e) {
      if (this.form.apply_range == 20 && this.product_list.length) {
        this.$message.success("商户信息已变更，请重新设置指定商品")
      }
      this.exclude_ids = [];
      this.product_list = [];
    }
  }
};
</script>

<style lang="scss" scoped>
.mb10 {
  margin-bottom: 10px;
}

.product-add {
  padding-bottom: 50px;
}

.tips {
  color: #ccc;
}
</style>
